//
//  KRLCountrySearchTableViewController.m
//  KaraLive
//
//  Created by Zhijia Zhong on 2018/9/13.
//  Copyright © 2018年 naxigoren. All rights reserved.
//

#import "KRLCountrySearchTableViewController.h"
#import "KRLCountryModel.h"

@interface KRLCountrySearchTableViewController ()

@property (nonatomic, strong) NSArray *searchResults;

@property (nonatomic, strong) NSString *cellReuseIdentifier;

@end

@implementation KRLCountrySearchTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.cellReuseIdentifier = @"KRLCountryCell";
    self.tableView.rowHeight = 40;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:self.cellReuseIdentifier];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.searchBar resignFirstResponder];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchResults.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellReuseIdentifier forIndexPath:indexPath];

    KRLCountryModel *country = self.searchResults[indexPath.row];
    cell.textLabel.text = country.name;
    cell.imageView.image = country.icon;

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self dismissViewControllerAnimated:YES completion:nil];

    if ([self.delegate respondsToSelector:@selector(didSelectCountry:)]) {
        KRLCountryModel *country = self.searchResults[indexPath.row];
        [self.delegate didSelectCountry:country];
    }
}

#pragma mark - UISearchResultsUpdating

//每输入一个字符都会执行一次
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF.name CONTAINS[c] %@", searchController.searchBar.text];
    self.searchResults = [NSMutableArray arrayWithArray:[_countrys filteredArrayUsingPredicate:preicate]];
    [self.tableView reloadData];
}

@end
